package com.ruoyi.kenuo.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.kenuo.domain.KernelApply;
import com.ruoyi.kenuo.service.IKernelApplyService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 好友申请Controller
 *
 * @author polo tang
 * @date 2023-09-05
 */
@RestController
@RequestMapping("/kenuo/apply")
public class KernelApplyController extends BaseController
{
    @Autowired
    private IKernelApplyService kernelApplyService;
    @Autowired
    private ISysUserService userService;
    /**
     * 查询好友申请列表
     */
   // @PreAuthorize("@ss.hasPermi('kenuo:apply:list')")
    @GetMapping("/list")
    public TableDataInfo list(KernelApply kernelApply)
    {
        startPage();
        List<KernelApply> list = kernelApplyService.selectKernelApplyList(kernelApply);
        return getDataTable(list);
    }
    /**
     * 查询好友申请列表
     * 不带分页，并且数据是初始状态的
     *
     */
    @GetMapping("/getMyList")
    public AjaxResult getMyList(KernelApply kernelApply)
    {
        kernelApply.setIsAgree(0);
        List<KernelApply> list = kernelApplyService.getMyList(kernelApply);
        return AjaxResult.success(list);
    }
    /**
     * 导出好友申请列表
     */
    @PreAuthorize("@ss.hasPermi('kenuo:apply:export')")
    @Log(title = "好友申请", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, KernelApply kernelApply)
    {
        List<KernelApply> list = kernelApplyService.selectKernelApplyList(kernelApply);
        ExcelUtil<KernelApply> util = new ExcelUtil<KernelApply>(KernelApply.class);
        util.exportExcel(response, list, "好友申请数据");
    }

    /**
     * 获取好友申请详细信息
     */
    @PreAuthorize("@ss.hasPermi('kenuo:apply:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(kernelApplyService.selectKernelApplyById(id));
    }

    /**
     * 新增好友申请
     */
    //@PreAuthorize("@ss.hasPermi('kenuo:apply:add')")
    @Log(title = "好友申请", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody KernelApply kernelApply)
    {
        //好友申请的时候，要进行去重，并返回给前端错误提醒信息
        String docn = kernelApply.getFromName();
        String hun = kernelApply.getToName();

        if(StringUtils.isEmpty(docn)||StringUtils.isEmpty(hun)){
            return AjaxResult.error("the parameter 'fromName' or 'toName' is empty");
        }
        KernelApply kay = new KernelApply();
        kay.setFromName(docn);
        kay.setToName(hun);
        kay.setIsAgree(2);
        //查询是否已经有拒绝的
        List<KernelApply> litThree = kernelApplyService.selectKernelApplyList(kay);
        if(litThree.size()>0){
            //如果有就拒绝的，先清除拒绝的状态
            kernelApplyService.deleteByName(kay);
        }
        //查询是否已经同意的状态
        KernelApply kayOne = new KernelApply();
        kayOne.setIsAgree(1);
        kayOne.setFromName(docn);
        kayOne.setToName(hun);
        List<KernelApply> lit = kernelApplyService.selectKernelApplyList(kayOne);
        if(lit.size()>0){
            return AjaxResult.error("You have already applied for it and It's already a friend relationship");
        }
        //查询是否已经申请过了
        KernelApply kayTwo = new KernelApply();
        kayTwo.setFromName(docn);
        kayTwo.setToName(hun);
        kayTwo.setIsAgree(0);
        List<KernelApply> litt = kernelApplyService.selectKernelApplyList(kayTwo);
        if(litt.size()>0){
          return AjaxResult.error("You have already applied for it and cannot repeat the application");
        }else{
            //查询医生的userId
            SysUser docUser = userService.getUserByUserName(docn);
            if(ObjectUtil.isNotEmpty(docUser)){
                kernelApply.setRemarkOne(docUser.getUserId().toString());
            }
            //查询患者的userId
            SysUser hunUser = userService.getUserByUserName(hun);
            if(ObjectUtil.isNotEmpty(hunUser)){
                kernelApply.setRemarkTwo(hunUser.getUserId().toString());
            }
            return toAjax(kernelApplyService.insertKernelApply(kernelApply));
        }

    }

    /**
     * 修改好友申请
     */
    //@PreAuthorize("@ss.hasPermi('kenuo:apply:edit')")
    @Log(title = "好友申请", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody KernelApply kernelApply)
    {
        return toAjax(kernelApplyService.updateKernelApply(kernelApply));
    }

    /**
     * 删除好友申请
     */
    @PreAuthorize("@ss.hasPermi('kenuo:apply:remove')")
    @Log(title = "好友申请", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(kernelApplyService.deleteKernelApplyByIds(ids));
    }

    /**
     * 医生端发起添加我的患者申请，患者端点击同意或拒绝接口，不仅修改了状态，还同时添加了医患关系
     * @param kernelApply
     * @return
     */
    @PostMapping("/agreeAddPatient")
    public AjaxResult agreeAddPatient(@RequestBody KernelApply kernelApply)
    {
        if(ObjectUtil.isEmpty(kernelApply.getId())){
            return AjaxResult.error("id is null or It doesn't exist");
        }
        AjaxResult ar = kernelApplyService.agreeAddPatient(kernelApply);
        return ar;
    }
}
